package com.sls.api.game.servlet.downstream;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.sls.api.game.constant.Constant;
import com.sls.api.game.constant.ExCodeDes;
import com.sls.api.game.pojo.CardInfo;
import com.sls.api.game.pojo.UserInfo;
import com.sls.api.game.servlet.SuperServlet;
import com.sls.api.util.CreateXMLByDom4j;
import com.sls.api.util.DataDeal;
import com.sls.api.util.IpUtil;
import com.sls.api.util.OrganizeRespXmlData;
import com.sls.api.util.PropertiesUtil;
import com.sls.api.util.ResponseDataXmlFormat;
import com.sls.api.util.SecretKeyUtil;
import com.sls.api.util.UtilMD5Encryption;
import com.sls.core.common.CommonUtil;
import com.sls.core.socket.Head;
import com.sls.core.socket.SocketDTO;

/**
 * 提卡接口
 * 
 * @author cx
 * 
 */
public class GetCardInfoServlet extends SuperServlet {

	private static final long serialVersionUID = -7476593617918280424L;
	private static Logger log = Logger.getLogger(GetCardInfoServlet.class);

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setAttribute("org.eclipse.jetty.server.Request.queryEncoding",
				"UTF-8");
		resp.setContentType("text/html;charset=UTF-8");
		resp.setStatus(HttpServletResponse.SC_OK);
		log.info("下游请求参数：" + req.getQueryString());

		// 合作方用户账号
		String userNo = req.getParameter("userNo");
		if (StringUtils.isNotEmpty(userNo)) {
			userNo = userNo.trim();
		}

		// 商品编号
		String goodsId = req.getParameter("goodsId");
		if (StringUtils.isNotEmpty(goodsId)) {
			goodsId = goodsId.trim();
		}
		// 所需提货商品的数量
		String buyNum = req.getParameter("buyNum");
		if (StringUtils.isNotEmpty(buyNum)) {
			buyNum = buyNum.trim();
		}
		// 商品供货单价
		String unitPrice = req.getParameter("unitPrice");
		if (StringUtils.isNotEmpty(unitPrice)) {
			unitPrice = unitPrice.trim();
		}
		// 总价
		String totalPrice = req.getParameter("totalPrice");
		if (StringUtils.isNotEmpty(totalPrice)) {
			totalPrice = totalPrice.trim();
		}
		// 合作方订单编号
		String ptOrderNo = req.getParameter("ptOrderNo");
		if (StringUtils.isNotEmpty(ptOrderNo)) {
			ptOrderNo = ptOrderNo.trim();
		}
		// 合作方订单时间
		String ptOrderTime = req.getParameter("ptOrderTime");
		if (StringUtils.isNotEmpty(ptOrderTime)) {
			ptOrderTime = ptOrderTime.trim();
		}
		
		//最终购买用户IP
		String merchantIP = req.getParameter("merchantIP");
		if (StringUtils.isNotEmpty(merchantIP)) {
			merchantIP = merchantIP.trim();
		}
		
		// 签名字符串
		String sign = req.getParameter("sign");
		if (StringUtils.isNotEmpty(sign)) {
			sign = sign.trim();
		}

		boolean flag = this.validateData(userNo, goodsId, buyNum, unitPrice,
				totalPrice, ptOrderNo, ptOrderTime, sign, resp, req,merchantIP);
		if (flag) {
			try {
				String clientIp = IpUtil.getIpAddr(req);
				Gson gson = CommonUtil.gson();
				SocketDTO dto = orgGsonSocket(userNo, goodsId, buyNum,
						unitPrice, totalPrice, ptOrderNo, ptOrderTime,
						clientIp, req);

				Head head = dto.getHead();
				String resCode = head.getResponseCode();
				String resMsg = head.getResponseMessage();

				String body = dto.getBody();
				CardInfo cardInfo = null;
				if (StringUtils.isNotEmpty(body)) {
					cardInfo = gson.fromJson(body, CardInfo.class);

					String date = CreateXMLByDom4j.createDateString();
					String realPath = PropertiesUtil
							.getValue("bill.project.path");
					String folderName = PropertiesUtil
							.getValue("bill.folder.name");
					String filePath = realPath + File.separator + folderName
							+ File.separator + date + File.separator + date
							+ userNo + ".xml";
					CreateXMLByDom4j.createCheckAccountFile(filePath, userNo,
							ptOrderNo, "", goodsId, unitPrice, buyNum, "",
							totalPrice, date);
				}
				if (cardInfo == null) {
					ResponseDataXmlFormat.returnFailMsg(
							ExCodeDes.UNKNOW_ERROR.getCode(),
							ExCodeDes.UNKNOW_ERROR.getDescription(), resp);
					return;
				}
				if (!(Constant.SUCCESS.equals(resCode))) {
					resCode = ExCodeDes.UNKNOW_ERROR.getCode();
				}
				String xmlData = OrganizeRespXmlData.assembleXmlForGetCard(
						resCode, resMsg, cardInfo, ptOrderNo);
				log.info("（提卡交易）同步返回给下游的消息：" + xmlData);
				resp.getWriter().write(xmlData);
				resp.getWriter().flush();
				resp.getWriter().close();

			} catch (Exception e) {
				log.error(e.toString());
				ResponseDataXmlFormat.returnFailMsg(
						ExCodeDes.UNKNOW_ERROR.getCode(),
						ExCodeDes.UNKNOW_ERROR.getDescription(), resp);
			}
		}
	}

	/**
	 * 组织报文发送到服务端
	 * 
	 * @param userId
	 * @param userPwd
	 * @param goodsId
	 * @param cardnum
	 * @param ptOrderNo
	 * @param ptOrderTime
	 * @param sign
	 * @param req
	 * @return
	 */
	private SocketDTO orgGsonSocket(String userNo, String goodsId,
			String buyNum, String unitPrice, String totalPrice,
			String ptOrderNo, String ptOrderTime, String clientIp,
			HttpServletRequest req) {
		UserInfo user = new UserInfo();
		user.setUserNo(userNo);
		user.setGoodsId(goodsId);
		user.setBuyNum(buyNum);
		user.setPtOrderNo(ptOrderNo);
		user.setUnitPrice(unitPrice);
		user.setTotalPrice(totalPrice);
		user.setClientIp(clientIp);

		if (StringUtils.isNotEmpty(ptOrderTime)) {
			user.setPtOrderTime(ptOrderTime);
		}
		Head head = new Head();
		head.setRequestId(UUID.randomUUID().toString());
		head.setServiceCode(Constant.GET_CARD);
		head.setIp(IpUtil.getIpAddr(req));
		head.setUserId(userNo);

		return super.send(head, user);
	}

	/**
	 * 数据校验
	 * 
	 * @param userNo
	 * @param userPwd
	 * @param goodsId
	 * @param buyNum
	 * @param unitPrice
	 * @param totalPrice
	 * @param ptOrderNo
	 * @param ptOrderTime
	 * @param sign
	 * @param resp
	 * @param req
	 * @return
	 * @throws IOException
	 */
	private boolean validateData(String userNo, String goodsId, String buyNum,
			String unitPrice, String totalPrice, String ptOrderNo,
			String ptOrderTime, String sign, HttpServletResponse resp,
			HttpServletRequest req,String merchantIP) throws IOException {
		boolean result = false;
		if (StringUtils.isEmpty(userNo)) {
			log.info("提卡交易时,合作方用户账号为空!!!");
			ResponseDataXmlFormat.returnFailMsg(
					ExCodeDes.PARAMETER_EMPTY.getCode(),
					ExCodeDes.PARAMETER_EMPTY.getDescription() + "[userId]!",
					resp);
			return false;
		} else if (StringUtils.isEmpty(goodsId)) {
			log.info("提卡交易时,商品编号为空!!!");
			ResponseDataXmlFormat.returnFailMsg(
					ExCodeDes.PARAMETER_EMPTY.getCode(),
					ExCodeDes.PARAMETER_EMPTY.getDescription() + "[goodsId]!",
					resp);
			return false;
		} else if (StringUtils.isEmpty(buyNum)) {
			log.info("提卡交易时,所需提货商品的数量为空!!!");
			ResponseDataXmlFormat.returnFailMsg(
					ExCodeDes.PARAMETER_EMPTY.getCode(),
					ExCodeDes.PARAMETER_EMPTY.getDescription() + "[buyNum]!",
					resp);
			return false;
		} else if (StringUtils.isEmpty(unitPrice)) {
			log.info("提卡交易时,商品供货单价为空!!!");
			ResponseDataXmlFormat
					.returnFailMsg(ExCodeDes.PARAMETER_EMPTY.getCode(),
							ExCodeDes.PARAMETER_EMPTY.getDescription()
									+ "[unitPrice]!", resp);
			return false;
		} else if (StringUtils.isEmpty(totalPrice)) {
			log.info("提卡交易时,商品的总价为空!!!");
			ResponseDataXmlFormat.returnFailMsg(
					ExCodeDes.PARAMETER_EMPTY.getCode(),
					ExCodeDes.PARAMETER_EMPTY.getDescription()
							+ "[totalPrice]!", resp);
			return false;
		} else if (StringUtils.isEmpty(ptOrderNo)) {
			log.info("提卡交易时,合作方订单编号为空!!!");
			ResponseDataXmlFormat
					.returnFailMsg(ExCodeDes.PARAMETER_EMPTY.getCode(),
							ExCodeDes.PARAMETER_EMPTY.getDescription()
									+ "[ptOrderNo]!", resp);
			return false;
		} else if (StringUtils.isEmpty(sign)) {
			log.info("提卡交易时,签名字符串为空!!!");
			ResponseDataXmlFormat.returnFailMsg(
					ExCodeDes.PARAMETER_EMPTY.getCode(),
					ExCodeDes.PARAMETER_EMPTY.getDescription() + "[sign]!",
					resp);
			return false;
		} else {
			StringBuilder builder = new StringBuilder();
			builder.append(userNo);
			builder.append(goodsId);
			builder.append(buyNum);
			builder.append(unitPrice);
			builder.append(totalPrice);
			builder.append(ptOrderNo);
			if (StringUtils.isNotEmpty(ptOrderTime)) {
				builder.append(ptOrderTime);
			}
			if (StringUtils.isNotEmpty(merchantIP)) {
				builder.append(merchantIP);
			}
			
			String secretKey = SecretKeyUtil.getInstance().getKey(userNo, req);
			if (StringUtils.isNotEmpty(secretKey)) {
				builder.append(secretKey);
			} else {
				ResponseDataXmlFormat.returnFailMsg(
						ExCodeDes.UNKNOW_ERROR.getCode(),
						ExCodeDes.UNKNOW_ERROR.getDescription(), resp);
				return false;
			}
			String data = builder.toString();

			boolean checked = UtilMD5Encryption.checkMD5SignatureOfUTF8(data,
					sign);
			if (checked) {
				result = true;
			} else {
				log.info("提卡交易时,数字签名验证失败!!!");
				ResponseDataXmlFormat.returnFailMsg(
						ExCodeDes.SIGN_FAIL.getCode(),
						ExCodeDes.SIGN_FAIL.getDescription(), resp);
				return false;
			}
		}

		boolean checkedTotal = DataDeal.checkTotalPrice(buyNum, unitPrice,
				totalPrice);
		if (checkedTotal) {
			result = true;
		} else {
			log.info("交易时,商品价格输入有误!!!");
			ResponseDataXmlFormat.returnFailMsg(
					ExCodeDes.PRICE_ERROR.getCode(),
					ExCodeDes.PRICE_ERROR.getDescription(), resp);
			result = false;
		}

		return result;
	}
}
